'- 
'-  teste1_0108231230_msx2+_screen12_conv.txt
'- 010808 - primeira tentativa no firstbasic-dos
'- input= 512x424 
'- output= 2x 53k scx (sx0,sx1) files

finp$="picture.jpg"

dim npaletr[16],npaletg[16],npaletb[16],grpltlev[16]

tmfl$="_tmpr01.gif"
shell("convert "+finp$+" -colors 4 "+tmfl$)

open tmfl$ for input as #1
for i=1 to 13:n=readbyte(1):next
for i=0 to 3
  n=readbyte(1):npaletr[i]=int((int(n/32))*(255/7))
  n=readbyte(1):npaletg[i]=int((int(n/32))*(255/7))
  n=readbyte(1):npaletb[i]=int((int(n/32))*(255/7))
  next
close #1
shell ("rm "+tmfl$)

for i=0 to 3:grpltlev[i]=int(((npaletr[i]*30)+(npaletg[i]*59)+(npaletb[i]*11))/100): next
for i=0 to 2
for j=i+1 to 3
if grpltlev[i]>grpltlev[j] then
  tmprq=grpltlev[i]:grpltlev[i]=grpltlev[j]:grpltlev[j]=tmprq
  tmprq=npaletr[i]:npaletr[i]=npaletr[j]:npaletr[j]=tmprq
  tmprq=npaletg[i]:npaletg[i]=npaletg[j]:npaletg[j]=tmprq
  tmprq=npaletb[i]:npaletb[i]=npaletb[j]:npaletb[j]=tmprq
end if
next:next

f2$=finp$+".a06":f3$=finp$+".b06"
xed=512:yed=424
setdisplay(xed,yed,32,1):paper(8^8-1):ink(0):pen(0):cls
loadimage(finp$,1):pasteicon(0,0,1)
open f2$ for output as #2:open f3$ for output as #3
for i=2 to 3:writebyte(i,254):next
for i=2 to 3:for j=1 to 3:writebyte(i,0):next:next
for i=2 to 3:writebyte(i,106):next
for i=2 to 3:for j=1 to 2:writebyte(i,0):next:next

for yp=0 to yed-1
  setcaption("line "+str$(yp)+"/423")
  for x=0 to xed-1
    c=point(x,yp)
    ri=bitwiseand((int(c/65536)),0xFF)
    gi=bitwiseand((int(c/256  )),0xFF)
    bi=bitwiseand(c,0xFF)
    
    dbuf=999:didv=0
    for i=0 to 3
      rdist=abs(npaletr[i]-ri):gdist=abs(npaletg[i]-gi):bdist=abs(npaletb[i]-bi)
      rgbdist=sqr((rdist^2)+(gdist^2)+(bdist^2))
      if rgbdist<=dbuf then:
        dbuf=rgbdist
        didv=i
        end if
      next

    if (x mod 4)=0 then:ci=(didv*64):end if
    if (x mod 4)=1 then:ci=bitwiseor(ci,(didv*16)):end if
    if (x mod 4)=2 then:ci=bitwiseor(ci,(didv*4)):end if
    if (x mod 4)=3 then:
      ci=bitwiseor(ci,didv)
      if (yp mod 2)<1 then:
        writebyte(2,ci)
      else
        writebyte(3,ci)
        end if

      end if    
    next:next
close #2:close #3

plt$=""
for i=0 to 3
  plt$=plt$+str$(int(npaletr[i]/32))+","+str$(int(npaletg[i]/32))+","+str$(int(npaletb[i]/32)) 
  if i<15 then:plt$=plt$+",":end if
  next

open finp$+"_autoexec.bas" for output as #1
print #1,"100 SCREEN0:WIDTH40:SCREEN6,,,,,0:COLOR 1,3,0:CLS\r"
print #1,"102 DATA "+plt$+"\r"
print #1,"104 RESTORE102:FOR C=0 TO 3:READ R,G,B:COLOR=(C,R,G,B):NEXT\r"
print #1,"200 A$=\""+ucase$(finp$)+"\":VDP(10)=VDP(10) OR 12\r"
print #1,"206 FOR I=0 TO 1:SET PAGE I,I:CLS:NEXT\r"
print #1,"208 SET PAGE ,0:BLOAD A$+\".A06\",S\r"
print #1,"210 SET PAGE ,1:BLOAD A$+\".B06\",S\r"
print #1,"212 IF INKEY$<>CHR$(27) THEN GOTO 212\r"
print #1,"214 VDP(10)=VDP(10) AND 243:STOP\r"
print #1,"216 SAVE\"AUTOEXEC.BAS\",A\r"
close #1

setcaption("done")


